package com.example.mywood;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

import adapter.MyAdapter;
import bean.ContentDataBean;
import myapp.MyApp;
import util.MyLog;
import util.SystemStatusManager;
import util.saveImagUtil;

@SuppressLint("SetJavaScriptEnabled")
public class ImageActivity extends FragmentActivity {


    MyApp m = null;
    private Context mcontext;
    private String imgurl;
    private ViewPager viewpager;
    private TextView tv_saveimg;
    private ContentDataBean.DataBean textContent;
    final List<String> bannerListImage = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        m = (MyApp) getApplicationContext();
        setTranslucentStatus();
        ArrayList<Activity> activityList = m.getActivity();
        activityList.add(this);

        mcontext = this;
        SharedPreferences spuserInfo = mcontext.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
        String textData = spuserInfo.getString("textData", "");
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        Intent intent = getIntent();
        //获取订单编号
        imgurl = intent.getStringExtra("img");
        String item = intent.getStringExtra("position");
        int position = Integer.parseInt(item);
        final List<String> b = intent.getStringArrayListExtra("imgs");
        if (b != null) {
            bannerListImage.addAll(b);
        }
        tv_saveimg = findViewById(R.id.tv_saveimg);
        if (textContent != null) {
            tv_saveimg.setText(textContent.getSave());
        }



		/*RelativeLayout rl_bg = (RelativeLayout) findViewById(R.id.rl_bg);
		rl_bg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});*/

        LinearLayout img_back = findViewById(R.id.img_back);
        img_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                MyLog.e("888888888888", "8888888888888");
                finish();
            }
        });

        ImageView img = (ImageView) findViewById(R.id.img_img);
        Glide.with(mcontext)
                .load(imgurl + "?x-oss-process=image/resize,w_520")
                .into(img);

//		final BannerView banner = (BannerView) findViewById(R.id.banner);
//		banner.setImageLoader(new GlideImageLoader());
//		banner.setImages(bannerListImage);
//		banner.start();
//		banner.onPageSelected(position+1);
//		banner.isAutoPlay(false);
//		banner.setCurrentPosition(position+1);
        viewpager = findViewById(R.id.viewpager);
        MyAdapter adapter = new MyAdapter(mcontext, bannerListImage);
        viewpager.setAdapter(adapter);
        int aa = (bannerListImage.size()) * 100;
        int bb = aa + position;
        MyLog.e("当前下标", aa + "   " + position + "   " + bb);
        viewpager.setCurrentItem(bb);
//		viewpager.setCurrentItem(position%bannerListImage.size());
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tv_saveimg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ActivityCompat.checkSelfPermission(ImageActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    showPermissionDialogBeforeRequest();
                } else {
                    requestPermission();
                }
            }
        });

    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(ImageActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
    }

    private void showPermissionDialogBeforeRequest() {
        new AlertDialog.Builder(this).setTitle(getString(R.string.help)).setMessage("为了保存图片，我们将会申请以下权限：\r\n" +
                        "存储权限：此权限是为了让您可以从图片保存到手机相册")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        requestPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1000) {
            for (int i = 0; i < grantResults.length; i++) {
                if (PackageManager.PERMISSION_GRANTED != grantResults[i]) {
                    return;
                }
            }
            int size = bannerListImage.size();
            int currentItem = viewpager.getCurrentItem();
            int a = currentItem % 100;
            int b = 0;
            int item = 0;
            if (a < size) {
                //说明a就是下标
                item = a;
                Log.e("下标1", a + "    下标   " + size);
            } else {
                b = a % size;
                item = b;
                Log.e("下标2", a + "    下标   " + size);
            }

            Log.e("下标----", item + "    下标");
            saveImagUtil.showDiaLog(ImageActivity.this, bannerListImage.get(item), textContent);
        }
    }

    public class GlideImageLoader extends ImageLoader {

        @Override
        public ImageView createImageView(Context context) {
            ImageView imageView = new ImageView(context);
            return imageView;
        }

        @Override
        public void displayImage(Context mContext, Object path, ImageView imageView) {

//            Glide.with(getApplicationContext())
// .load(path)
// .transform(new CenterCrop(context), new GlideRoundTransform(context))
// .into(imageView);
            Glide.with(getApplicationContext()).load(path).into(imageView);
			/*Glide.with(getApplicationContext())
					.load(path)
					.transform(new CenterCrop(mContext), new GlideRoundTransform(mContext))
					.crossFade()
					.into(imageView);*/
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            finish();
            return false;
        }
        return false;
    }


    /**
     * 设置状态栏背景状态
     */
    public void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }


}
